package cn.afactory.tygz.ui.sns.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.model.SnsTopicInfo;
import cn.afactory.tygz.model.SnsTopicInfoList;
import cn.afactory.tygz.model.SnsUserInfo;
import cn.afactory.tygz.ui.base.BaseFragment;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.sns.PublishSubjectActivity;
import cn.afactory.tygz.ui.sns.TopicListActivity;
import cn.afactory.tygz.ui.sns.adapter.TopicListAdapter;
import cn.afactory.tygz.ui.sns.controller.SnsControler;

public class TopicListFragment extends BaseFragment implements TopicListAdapter.OnItemClickListener {
    private static final String TAG = TopicListFragment.class.getSimpleName();

    protected SnsControler mController;
    protected TopicListAdapter mAdapter;

    private LayoutInflater minflater;
    protected int mPageIndex = 1;
    protected int mPageSize = 10;
    private int mType = 0;
    private int mSelectType = 0;
    protected List<SnsTopicInfo> mList = new ArrayList<SnsTopicInfo>();

    public TopicListFragment(int type,int selectType) {
        mType = type;
        mSelectType = selectType;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mController = new SnsControler(mContext, mUIHandler, null);
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        this.minflater = inflater;
        View mlayout = inflater.inflate(R.layout.fragment_health_subject, null);
        initViews(mlayout);
        showTitleBar(false);
        return mlayout;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SnsControler.MSG_GET_TOPIC_LIST_OK:
                if (msg.obj instanceof SnsTopicInfoList) {
                    hideErrorPage(-1);
                    SnsTopicInfoList t = (SnsTopicInfoList) msg.obj;
                    if (t.value != null && t.value.size() >= 0) {
                        try {
                            mList.addAll(t.value);
                            //是否显示置顶链接VIEW
                            mAdapter.setData(mList);
                            mPageIndex = (mList.size()/mPageSize) + 1;
                            setListListener();

                            if (plistview.isRefreshing()) {
                                plistview.onRefreshComplete();
                            }
                            if (t.value.size() < mPageSize) {
                                plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            } else {
                                plistview.setMode(PullToRefreshBase.Mode.BOTH);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (mAdapter.getCount() == 0) {
                            showNullPage(true);
                        }
                    }
                }
                break;
            case SnsControler.MSG_GET_TOPIC_LIST_KO:
                if (mAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadUserList(true);
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, (String)msg.obj);
                }
                break;
        }

        // 结束下拉刷新
        if (plistview.isRefreshing()) {
            plistview.onRefreshComplete();
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    /**
     * 初始化组件 views
     *
     * @param view
     */
    private void initViews(View view) {
        plistview = (PullToRefreshListView) view.findViewById(R.id.plv_subject);
        initListView();
    }

    /**
     * 加载listview数据
     */
    protected void startLoadUserList(boolean cleanData) {
        if (cleanData) {
            mList.clear();
            mPageIndex = 1;
        }

        mAdapter = new TopicListAdapter(getActivity(),mList,mSelectType);
        plistview.setAdapter(mAdapter);
        mController.doGetMyTopicList(SPUtils.getUid(mContext),mType,mPageIndex, mPageSize);
    }

    /**
     * 初始化list view
     */
    private void initListView() {
        mAdapter = new TopicListAdapter(mContext, null,mSelectType);
        plistview.setAdapter(mAdapter);
        plistview.setMode(PullToRefreshBase.Mode.BOTH);
        setListListener();
        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadUserList(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadUserList(false);
            }
        });
    }

    protected void setListListener() {
        plistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView lv = plistview.getRefreshableView();
                // 除去 header counter
                if (position >= lv.getHeaderViewsCount()) {
                    position -= lv.getHeaderViewsCount();
                    if (mAdapter.getItem(position) instanceof SnsTopicInfo) {
                        if(mSelectType == TopicListActivity.TYPE_CHOOSE_TOPIC_ID){
                            //选择话题
                            Intent intent = new Intent();
                            intent.putExtra(SPUtils.EXTRA_DATA,mList.get(position));
                            getActivity().setResult(Activity.RESULT_OK,intent);
                            getActivity().finish();
                        }else{
                            //跳转到话题详情页
                            NaviUtils.gotoTopicDetailActivity(getActivity(),mList.get(position));
                        }
                    }
                }
            }
        });

        mAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onResume() {
        startLoadUserList(true);
        super.onResume();
    }

    @Override
    public void OnAttentionClick(TextView v, SnsTopicInfo snsTopicInfo) {
        mController.doFollowTopic(v,snsTopicInfo);
    }

    @Override
    public void onCancelAttentionClick(TextView v, SnsTopicInfo snsTopicInfo) {
        mController.doUnFollowTopic(v,snsTopicInfo);
    }
}